package com.smallprogram.www.exception;

import com.smallprogram.www.entity.ResultEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统异常处理
 */
@ControllerAdvice
public class MyControllerAdvice {
    private static final Logger log = LoggerFactory.getLogger(ControllerAdvice.class);

    /**
     * 全局异常捕获处理
     * @param ex
     * @return
     */
    @ExceptionHandler(value=Exception.class)
    public ModelAndView errorHandler(Exception ex){
        log.info(ex.getMessage());
        System.out.println("-----------------全局异常捕获处理----------------------");
        ex.printStackTrace();
        System.out.println("-----------------全局异常捕获处理end------------");
        return new  ModelAndView("error");
    }
    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param myEx
     * @return
     */
    @ExceptionHandler(value=MyException.class)
    @ResponseBody
    public String myErrorHandler(MyException myEx){
        log.info(myEx.getMessage());
        System.out.println("-----------------全局自定义异常捕获处理----------------------");
        myEx.printStackTrace();
        System.out.println("-----------------全局自定义异常捕获处理end------------");
        ResultEntity<Object> resultEntity = new ResultEntity<Object>(myEx.getCode(),"系统异常");
        return resultEntity.toString();
    }
}
